<template>
  <div>
      <el-form :model="form" :rules="rules" ref="form" label-width="80px" >
        <el-form-item label="商品标题" prop="title">
            <el-input v-model="form.title" maxlength="15" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="一口价" prop="price">
            <el-input v-model="form.price" style="width:100px"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <div class="type-list">
            <el-row :gutter="20" v-for="(item,index) in form.spec" :key="index">
              <el-col :span="6">
                <el-input placeholder="规格名称" v-model="item.title"></el-input>
              </el-col>
              <el-col :span="3">
                <el-input placeholder="规格价格" v-model="item.price"></el-input>
              </el-col>
              <el-col :span="3">
                <el-input placeholder="库存" v-model="item.num"></el-input>
              </el-col>
              <el-col :span="4">
                <el-button v-show="form.spec.length > 1" type="danger" size="small" icon="el-icon-minus" @click="delSpec(index)"></el-button>
                <el-button v-show="index === form.spec.length - 1" type="success" size="small" icon="el-icon-plus" @click="addSpec"></el-button>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="主图" prop="mainPic">
          <div class="mainpic-show">
            <div class="mainpic-item" v-for="(item,index) in form.mainPic" :key="index" @mouseenter="delIndex = index" @mouseleave="delIndex = -1">
              <img :src="`${$api.baseURL}${item}`" />
              <div class="el-icon-delete mainpic-del-btn" :class="{'delbtn-active': index === delIndex}" @click="delMainpic(index)"></div>
            </div>
            <el-upload v-if="form.mainPic.length < 5"
                       :action="`${$api.baseURL}/admin/upload/img`"
                       name="img"
                       multiple
                       :limit="5"
                       :show-file-list="false"
                      :before-upload="beforeUpload"
                      :on-success="onSuccess"
                      :on-error="onError"
                      :on-exceed="onExceed"
                       >
                <div class="el-icon-plus upload-btn"></div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="商品详情" prop="details">
            <div id="editor"></div>
        </el-form-item>
        <el-form-item label="是否上架">
          <el-radio v-model="form.state" label="1">上架</el-radio>
          <el-radio v-model="form.state" label="2">下架</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
import Editor from 'wangeditor'
export default {
  data(){
    //价格的校验
    let checkPrice = (rule, value, cb)=>{
      if(!isNaN(value)){
        if(value <= 0){
          cb(new Error('价格必须大于0'))
        }else{
          cb()
        }
      }else{
        cb(new Error('价格必须为数字！'))
      }
    }

    //规格的校验
    let checkSpec = (rule, value, cb)=>{
      for(var i=0; i<value.length;i++){
          let item = value[i]
          // console.log(item);
          if(item.title.trim() === ''){
            // console.log('no');
           return cb(new Error('规格名称不能为空'))
          }
          if(item.price.trim() === ''){
            return  cb(new Error('规格价格不能为空'))
          }
          if(item.num.trim() === ''){
            return  cb(new Error('库存不能为空'))
          }
      }

      cb()
    }

    return {
      editor: null,
      delIndex: -1,
      form: {
        title: '',
        price: '',
        spec: [
          {title: '', price: '', num: ''}
        ],
        mainPic: [],
        details: '',
        state: '1'
      },
      rules: {
        title: [
          {required: true, message: '商品标题不能为空'}
        ],
        price: [
          {required: true, message: '商品价格不能为空'},
          { validator: checkPrice }
        ],
        spec: [
          {type: 'array', required:true, message: '至少要有一个商品规格'},
          { validator: checkSpec }
        ],
        mainPic: [
          {type: 'array', required: true, message:'至少要上传一张主图'}
        ],
        details: [
          {required: true, message: '详情不能为空'}
        ]
      }
    }
  },
  mounted(){
      //初始化富文本编辑器
      this.editor = new Editor("#editor")
      // 配置 server 接口地址
      this.editor.config.uploadImgServer = this.$api.baseURL + '/admin/upload/editor/img'
      this.editor.config.uploadFileName = 'editorImg'
      //回调函数
      this.editor.config.uploadImgHooks = {
        customInsert: (cb,result)=>{
          // console.log(result);
          this.$message({
            type: result.code === 200 ?'success':'error',
            message: result.msg
          })

          if(result.code === 200){
            let url = this.$api.baseURL + result.path
            cb(url)
          }
        }
      }

      // 配置 onchange 回调函数
      this.editor.config.onchange = (newHtml) => {
        this.form.details = newHtml
      };
      // 配置触发 onchange 的时间频率，默认为 200ms
      this.editor.config.onchangeTimeout = 500; // 修改为 500ms

      this.editor.create()
  },
  watch:{
    form: {
      handler(newForm,oldForm){
        // console.log(newForm,oldForm);
      },
      deep: true
    },
    money(v1,v2){
        // console.log(v1,v2);
    }
  },
  methods: {
    submit(){ //提交事件
      this.$refs.form.validate((valid)=>{
        if(!valid){
          this.$message({
            type: 'error',
            message: '提交失败'
          })
          return false
        }

        // this.form.details = this.editor.txt.html()
        // console.log(this.form);

        this.$http({
          path: this.$api.Goods.add,
          method: 'post',
          params: {
            data: JSON.stringify(this.form)
          }
        }).then(res=>{
          // console.log(res);
          this.$message({
            type: res.code === 200 ? 'success':'error',
            message: res.msg
          })
          if(res.code === 200){
            this.form = {
              title: '',
              price: '',
              spec: [
                {title: '', price: '', num: ''}
              ],
              mainPic: [],
              details: '',
              state: '1'
            }
            this.editor.txt.clear()
          }
        })

        return true
      })
    },
    addSpec(){ //添加规格
      this.form.spec.push({
        title: '',
        price: '',
        num: ''
      })
    },
    delSpec(index){ //删除规格
      this.form.spec.splice(index,1)
    },
    beforeUpload(file){ //上传前钩子
        // console.log(file);
        let type = file.type === 'image/jpeg' || file.type === 'image/png'
        let size = file.size < 1024 * 1024

        if(!type){
          this.$message.warning('只能上传图片！')
        }else if(!size){
          this.$message.warning('图片不能大于1MB！')
        }

        return type && size
    },
    onSuccess(res){ //上传成功
        if(res.code === 200){
          this.form.mainPic.push(res.path)
        }else{
          this.$message.error('上传失败')
        }
    },
    onError(err){ //上传失败
      this.$message.error('主图上传失败')
    },
    onExceed(){ //选择主图时超出数量限制
      this.$message.warning('最多只能选5张图片')
    },
    delMainpic(index){ //删除主图
      this.form.mainPic.splice(index,1)
    }
  }
}
</script>

<style scoped>
.type-list{
  display: flex;
  flex-direction: column;
}
.el-row{
  margin: 10px 0px;
}
.upload-btn{
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 10px;
  font-size: 30px;
  color: #bbb;
  display: flex;
  align-items: center;
  justify-content: center;
}
.mainpic-show{
  display: flex;
  align-items: center;
}
.mainpic-item{
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 10px;
  margin: 10px;
  position: relative;
  overflow: hidden;
}
.mainpic-item img{
  width: 100%;
}
.mainpic-del-btn{
  z-index: 10;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  align-items: center;
  justify-content: center;
  font-size: 26px;
  color: #fff;
  cursor: pointer;
}
.delbtn-active{
  display: flex;
}
</style>